<template>
  <div>
    <el-table border v-loading="loading"
    :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
    style="width: 100%">
    <el-table-column label="编号" prop="id">
    </el-table-column>
    <el-table-column label="姓名" prop="name"></el-table-column>
    <el-table-column label="生日" prop="bir" sortable ></el-table-column>
    <el-table-column label="性别" prop="sex"></el-table-column>
    <el-table-column label="地址" prop="address"></el-table-column>
    <el-table-column label="" align="center">
        <template slot="header" slot-scope="scope">
        <el-input
          v-model="search"
          size="mini"
          placeholder="输入姓名的关键字搜索"/>
        </template>
        <template slot-scope="scope">
            <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            
            <el-popconfirm
              @confirm="handleDelete(scope.$index, scope.row)"
              confirm-button-text='好的'
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该用户信息吗？"
            >
              <el-button slot="reference" size="mini" type="danger">删除</el-button>
            </el-popconfirm>
        </template>
    </el-table-column>
  </el-table>
  <br>
  <el-row>
    <el-col :span='1'>
      <el-button type="success" plain size="medium" @click="add">添加</el-button>
    </el-col>
    
    <el-col :span='5' :push="5">

     <!-- 分页组件 -->
      <el-pagination
        small
        @current-change="findPage"
        @size-change="findSize"
        background
        layout="total,prev, pager, next,jumper,sizes"
        :total="pagination.total" :page-size="pagination.pageSize" :page-sizes="[5,6,7,8]"
        :current-page="pagination.currentPage">
      </el-pagination>
    </el-col>
  </el-row>
  
<!-- 添加编辑组件 -->
    <el-dialog :title="addOrUpdate" :visible.sync="dialogFormVisible" :lock-scroll="true" :before-close="handleClose" center>
      <el-form :model="form" :label-position="right" label-width="auto" :rules="rule" ref="ruleForm">
          <el-form-item label="姓名" prop="name">
            <el-col :span="12"><el-input placeholder="请输入姓名" v-model="form.name"></el-input></el-col>
          </el-form-item>

          <el-form-item label="出生日期" prop="bir">
            <el-col :span="12">
              <el-date-picker v-model="form.bir" type="date" placeholder="请选择日期" style="width: 100%"
                          :picker-options="pickerOptions">
            </el-date-picker>
            </el-col>
          </el-form-item>

          <el-form-item label="性别">
            <el-radio v-model="form.sex" label="男"></el-radio>
            <el-radio v-model="form.sex" label="女"></el-radio>
          </el-form-item>

          <el-form-item label="家庭地址" prop="address">
            <el-col :span="12"><el-input placeholder="请输入家庭地址" type="textarea" autosize v-model="form.address"></el-input></el-col>
          </el-form-item>

          <el-button @click="cancel('ruleForm')" class="el-button-child">取 消</el-button>
          <el-button type="primary" @click="addConfirm('ruleForm')" :disabled="showAdd" class="el-button-child">添 加</el-button>
         <el-button type="primary" @click="updateConfirm('ruleForm')" :disabled="showUpdate" class="el-button-child">更 新</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'List',
    data() {
      return {
        addOrUpdate:"",//判断弹出来的表单是添加还是更新
        showAdd: true,//关闭添加开关
        showUpdate: true,//关闭更新开关
        tableData: [],//表的数据
        search: '',//又上角的搜索内容
        loading: false,//关闭等待
        dialogFormVisible:false,//添加或更新的表单默认关闭
        form: {//添加或删除的表单
          name: '',
          bir: '',
          sex: '男',
          address:''
        },
        pagination: {//分页相关模型数据
          currentPage: 1,//当前页码
          pageSize:5,//每页显示的记录数
          total:0,//总记录数
        },
        pickerOptions:{//控制时间的事件
          disabledDate(time) {//禁止选择今天之后的日期
            return time.getTime() > Date.now();
          }
        },
        rule: {//控制表单的容错处理
          name:[
            {required: true, message:'请输入姓名', trigger: 'blur'}
          ],
          bir:[
            {required: true, message: '请选择日期', trigger: 'change'}
          ],
          address:[
            {required: true, message: '请输入家庭地址', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      findSize(size){//每页最多好多条数据
        this.pagination.pageSize = size;
        this.findAll();
      },
      findPage(page){//前往第多少页
        this.pagination.currentPage = page;
        this.findAll();
      },
      findAll(){//根据查询表单
        var parm = '?';
        parm += 'currentPage='+this.pagination.currentPage;
        parm += '&pageSize='+this.pagination.pageSize;
        this.$axios.get("http://localhost:8989/user/findAll"+parm).then(
            res=>{
                if(res.data.status){
                  this.tableData = res.data.user.records;
                  this.pagination.currentPage = res.data.user.current;
                  this.pagination.total = res.data.user.total;
                  this.pagination.pageSize = res.data.user.size;
                }
            }
        )
      },
      add(){//弹出添加信息的表单
        this.addOrUpdate = "添加信息";
        this.dialogFormVisible = true;
        this.showAdd = false;
      },
      handleEdit(index, row) {//弹出编辑信息的表单
        // var row1 = row;
        this.addOrUpdate = "更新信息";
        this.dialogFormVisible = true;
        this.$axios.get("http://localhost:8989/user/selectOne?id="+row.id).then(
          res=>{
            if(res.status==200){
              this.form = res.data;//将编辑的这条信息原始值给到表单
            }else{
              this.$notify({
                title: '网页提示',
                message: h('i',{style:'color: teal'},'编辑失败，请刷新页面再试...'),
                duration: 1000
              });
              this.dialogFormVisible = false;
              this.showAdd = true;
            }
          }
        )
        this.showUpdate = false;
        // console.log(index, row);
      },
      handleDelete(index, row) {//删除这一条信息
        // console.log(index, row);
        this.$axios.get("http://localhost:8989/user/delete?id="+row.id).then(
          res=>{
            if(res.data.status){
              this.$message({
                showClose: true,
                message: '恭喜你，'+res.data.msg,
                type: 'success'
              });
              this.findAll();
              }else{
                this.$message({
                    showClose: true,
                    message: res.data.msg,
                    type: 'error'
                })
              }
          }
        )
      },
      cancel(formName){//取消编辑或者添加
        this.showAdd = true;
        this.showUpdate = true;
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();//重置表单
      },
      addConfirm(formName){//确认添加信息
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post("http://localhost:8989/user/add",this.form).then(
              res=>{
                if(res.data.status){
                  this.$message({
                    showClose: true,
                    message: '恭喜你，'+res.data.msg,
                    type: 'success'
                  })
                  // console.log(res);
                }else{
                  this.$message({
                    showClose: true,
                    message: res.data.msg,
                    type: 'error'
                  })
                }
              }
            )
            this.dialogFormVisible = false;
            this.showAdd = true;
            this.$refs[formName].resetFields();
            // this.form = {};
            this.findAll();
          } else {
            return false;
          }
        })
      },
      updateConfirm(formName){//确认更新信息
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log("进来了");
            this.$axios.post("http://localhost:8989/user/update",this.form).then(
              res=>{
                console.log(res);
                if(res.data.status){
                  this.$message({
                    showClose: true,
                    message: '恭喜你，'+res.data.msg,
                    type: 'success'
                  })
                  // console.log(res);
                }else{
                  this.$message({
                    showClose: true,
                    message: res.data.msg,
                    type: 'error'
                  })
                }
              }
            )
            this.dialogFormVisible = false;
            this.showUpdate= true;
            this.$refs[formName].resetFields();
            // this.form = {};
            this.findAll();
          } else {
            return false;
          }
        })
      },
      handleClose(done) {// 点击 表单右上角的×
        
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.showUpdate= true;
            this.showAdd= true; 
            this.$refs.ruleForm.resetFields();
          })
          .catch(_ => {});
         
      }
    },
    created(){//当刷新或者重新进入这个页面或者第一次进入这个页面时执行的操作
        // this.loading=true;
        // setTimeout(() => {this.loading=false;}, 800);
        this.findAll();
    }
}
</script>

<style>
.el-form-item{
  margin-left: 200px;
}
.el-button-child{
  margin-top: 30px;
  margin-left: 240px;
}

</style>